package com.wenkang.stu.config.security.handler;

import com.wenkang.stu.enums.ExceptionEnums;
import com.wenkang.stu.exception.KangException;
import com.wenkang.stu.util.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class LoginFailHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
        // 请求是否已经被处理
        if (response.isCommitted()) {
            log.debug("Response has already been committed");
            return;
        }
        // 获取错误
        Throwable cause = e.getCause();
        ExceptionEnums exceptionEnums;
        // 根据错误类型处理错误
        if (cause instanceof KangException) {
            KangException exception = (KangException) cause;
            exceptionEnums = exception.getExceptionEnums();
            ResponseUtils.ExceptionResult(response, exceptionEnums);
        } else {
            ResponseUtils.ExceptionResult(response, e.getMessage());
        }
    }
}
